<template>
  <!-- 公告跑马灯 -->
  <div v-if="!closed && notices.length" class="notice-bar">
    <div class="notice-icon"></div>
    <div
      class="notice-content"
      @mouseenter="pauseMarquee"
      @mouseleave="resumeMarquee"
    >
      <div class="marquee-wrapper" ref="wrapperRef">
        <div
          class="notice-text"
          :style="textStyle"
          @click="goNoticeDetail(currentNotice)"
        >
          {{ currentNotice.question }}
        </div>
      </div>
    </div>
    <div class="notice-close" @click="closed = true">x</div>
  </div>

  <!-- 只保留一个标题 -->
  <div class="section-header">
    <div class="title">{{ _t18('12_remen') }}{{ _t18(title) }}</div>
    <div class="more" @click="goQuote">{{ _t18('exchange_more') }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getHelpcenter } from '@/api/help/index'

const props = defineProps({
  title: { type: String, default: '' }
})

const router = useRouter()

// ======== 公告数据 ========
const notices = ref([])
const currentNotice = ref({})
const currentIndex = ref(0)
const closed = ref(false)

// ======== DOM & 动画控制 ========
const wrapperRef = ref(null)
const wrapperWidth = ref(0)
const textWidth = ref(0)
const offsetX = ref(0)
const speed = 30 // px/s
let rafId = null
let lastTime = 0
let isPaused = false
let pauseOffset = 0
let pauseTime = 0

// ======== 动态样式 ========
const textStyle = computed(() => ({
  transform: `translateX(${offsetX.value}px)`,
  transition: 'none',
  whiteSpace: 'nowrap'
}))

// ======== 加载公告 ========
async function loadNotices() {
  try {
    const res = await getHelpcenter()
    const arr = res.data?.[0]?.infoList || []
    if (arr.length === 0) return
    notices.value = arr
    currentIndex.value = 0
    currentNotice.value = arr[0]
  } catch (err) {
    console.error('加载公告失败', err)
  }
}

// ======== 切换下一条 ========
function nextNotice() {
  if (notices.value.length <= 1) return
  currentIndex.value = (currentIndex.value + 1) % notices.value.length
  currentNotice.value = notices.value[currentIndex.value]
  resetMarquee()
}

// ======== 重置跑马灯（新公告）========
async function resetMarquee() {
  cancelAnimationFrame(rafId)
  rafId = null
  offsetX.value = wrapperWidth.value // 从右侧进入
  await nextTick()
  measureTextWidth()
  startMarquee()
}

// ======== 测量文字宽度 ========
function measureTextWidth() {
  if (!wrapperRef.value) return
  const wrapper = wrapperRef.value
  const text = wrapper.querySelector('.notice-text')
  if (!text) return

  wrapperWidth.value = wrapper.offsetWidth
  textWidth.value = text.offsetWidth
}

// ======== 核心动画：从右到左滚动 ========
function animate(currentTime) {
  if (!lastTime) lastTime = currentTime
  const deltaTime = currentTime - lastTime
  lastTime = currentTime

  const deltaX = (speed * deltaTime) / 1000
  offsetX.value -= deltaX

  // 当文字完全移出左侧 → 切换下一条
  if (offsetX.value <= -textWidth.value) {
    nextNotice()
    return
  }

  rafId = requestAnimationFrame(animate)
}

// ======== 开始滚动 ========
function startMarquee() {
  if (rafId || !textWidth.value) return
  lastTime = performance.now()
  rafId = requestAnimationFrame(animate)
}

// ======== 暂停 ========
function pauseMarquee() {
  if (isPaused || !rafId) return
  isPaused = true
  pauseTime = performance.now()
  pauseOffset = offsetX.value
  cancelAnimationFrame(rafId)
  rafId = null
}

// ======== 恢复 ========
function resumeMarquee() {
  if (!isPaused) return
  isPaused = false
  const pausedDuration = performance.now() - pauseTime
  lastTime = performance.now() - pausedDuration
  offsetX.value = pauseOffset
  rafId = requestAnimationFrame(animate)
}

// ======== 跳转详情 ========
function goNoticeDetail(n) {
  if (n?.id) router.push(`/zxDetail/${n.id}`)
}

const goQuote = () => router.push('/quote')

// ======== 生命周期 ========
onMounted(async () => {
  await loadNotices()
  if (notices.value.length > 0) {
    await nextTick()
    measureTextWidth()
    offsetX.value = wrapperWidth.value
    startMarquee()
  }
})

onBeforeUnmount(() => {
  cancelAnimationFrame(rafId)
})

// ======== 窗口 resize 适配 ========
let resizeTimer = null
window.addEventListener('resize', () => {
  clearTimeout(resizeTimer)
  resizeTimer = setTimeout(() => {
    measureTextWidth()
    if (!isPaused) {
      offsetX.value = wrapperWidth.value
    }
  }, 100)
})
</script>

<style scoped>
/* 公告跑马灯 */
.notice-bar {
  width: 100%;
  padding: 10px 12px;
  background: #fff7e6;
  border-radius: 8px;
  margin-bottom: 14px;
  border: 1px solid #ffe7ba;
  display: flex;
  align-items: center;
  gap: 8px;
  overflow: hidden;
  position: relative;
}

.notice-icon {
  width: 18px;
  height: 18px;
  background-image: url('https://img.icons8.com/fluency/48/000000/megaphone.png');
  background-size: cover;
  flex-shrink: 0;
}

.notice-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.marquee-wrapper {
  overflow: hidden;
  width: 100%;   /* 已修复 */
}

.notice-text {
  color: #e67e22;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: inline-block;
}

.notice-close {
  font-size: 16px;
  font-weight: normal;
  color: #999;
  cursor: pointer;
  padding: 0 4px;
  flex-shrink: 0;
  user-select: none;
}

.notice-close:hover {
  color: #e67e22;
}

/* 标题栏（只保留一个） */
.section-header {
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 22px;
  color: #000;
  font-weight: 700;
  height: 28px;
  line-height: 28px;
  text-transform: capitalize;
}

.more {
  color: #999;
  font-size: 13px;
  cursor: pointer;
  transition: color 0.2s;
}

.more:hover {
  color: #333;
}
</style>